import React, { useState, useEffect, useRef } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { 
  Play, 
  RotateCcw,
  Terminal,
  Eye,
  ChevronRight,
  ChevronDown,
  Copy,
  Check
} from 'lucide-react';
import { DesignPattern, DemoState } from '@/types';
import Visualization from './Visualization';

interface DemoTabProps {
  pattern: DesignPattern;
  demoState: DemoState;
  onStart: () => void;
  onPause: () => void;
  onReset: () => void;
  onStep: () => void;
}

interface ConsoleMessage {
  id: number;
  type: 'log' | 'error' | 'warn' | 'info';
  content: string;
  timestamp: Date;
}

const DemoTab: React.FC<DemoTabProps> = ({
  pattern,
  demoState,
  onStart,
  onReset
}) => {
  const [isVisualizationExpanded, setIsVisualizationExpanded] = useState(true);
  const [consoleMessages, setConsoleMessages] = useState<ConsoleMessage[]>([]);
  const [isRunning, setIsRunning] = useState(false);
  const [copied, setCopied] = useState(false);
  const consoleRef = useRef<HTMLDivElement>(null);
  const messageIdRef = useRef(0);

  // 创建自定义console对象来捕获输出
  const createCustomConsole = () => {
    const addMessage = (type: ConsoleMessage['type'], ...args: any[]) => {
      const content = args.map(arg => 
        typeof arg === 'object' ? JSON.stringify(arg, null, 2) : String(arg)
      ).join(' ');
      
      const message: ConsoleMessage = {
        id: messageIdRef.current++,
        type,
        content,
        timestamp: new Date()
      };
      
      setConsoleMessages(prev => [...prev, message]);
    };

    return {
      log: (...args: any[]) => addMessage('log', ...args),
      error: (...args: any[]) => addMessage('error', ...args),
      warn: (...args: any[]) => addMessage('warn', ...args),
      info: (...args: any[]) => addMessage('info', ...args)
    };
  };

  // 执行演示代码
  const executeDemo = async () => {
    setIsRunning(true);
    setConsoleMessages([]);
    
    const customConsole = createCustomConsole();
    
    try {
      // 替换console对象
      const originalConsole = console;
      (window as any).console = customConsole;
      
      // 添加开始消息
      customConsole.info(`🚀 开始执行 ${pattern.name} 演示`);
      customConsole.log('=' .repeat(50));
      
      // 执行演示代码
      await new Promise(resolve => setTimeout(resolve, 500)); // 短暂延迟
      
      // 使用Function构造函数安全地执行代码
      const demoFunction = new Function('console', pattern.demoCode || '');
      demoFunction(customConsole);
      
      // 恢复原始console
      (window as any).console = originalConsole;
      
      customConsole.log('=' .repeat(50));
      customConsole.info('✅ 演示执行完成');
      
    } catch (error) {
      customConsole.error('❌ 执行出错:', error);
    } finally {
      setIsRunning(false);
    }
  };

  // 滚动到底部
  useEffect(() => {
    if (consoleRef.current) {
      consoleRef.current.scrollTop = consoleRef.current.scrollHeight;
    }
  }, [consoleMessages]);

  const handleStart = () => {
    executeDemo();
    onStart();
  };

  const handleReset = () => {
    setConsoleMessages([]);
    setIsRunning(false);
    onReset();
  };

  const handleCopyCode = async () => {
    try {
      await navigator.clipboard.writeText(pattern.demoCode || '');
      setCopied(true);
      setTimeout(() => setCopied(false), 2000);
    } catch (error) {
      console.error('复制失败:', error);
    }
  };

  const getMessageColor = (type: ConsoleMessage['type']) => {
    switch (type) {
      case 'error': return 'text-red-400';
      case 'warn': return 'text-yellow-400';
      case 'info': return 'text-blue-400';
      default: return 'text-green-400';
    }
  };

  return (
    <div className="min-h-full flex flex-col bg-gray-50">
      {/* Controls */}
      <div className="bg-white border-b border-gray-200 p-4">
        <div className="flex items-center justify-between">
          <div className="flex items-center space-x-4">
            <h2 className="text-lg font-semibold text-gray-900">交互式演示</h2>
            <div className="flex items-center space-x-2 text-sm text-gray-600">
              <div className={`w-2 h-2 rounded-full ${
                isRunning ? 'bg-green-500 animate-pulse' : 'bg-gray-400'
              }`}></div>
              <span>{isRunning ? '执行中...' : '就绪'}</span>
            </div>
          </div>
          
          <div className="flex items-center space-x-2">
            <motion.button
              onClick={handleStart}
              disabled={isRunning}
              className={`flex items-center space-x-2 px-4 py-2 rounded-lg transition-colors ${
                isRunning 
                  ? 'bg-gray-400 text-gray-600 cursor-not-allowed' 
                  : 'bg-green-600 text-white hover:bg-green-700'
              }`}
              whileHover={!isRunning ? { scale: 1.05 } : {}}
              whileTap={!isRunning ? { scale: 0.95 } : {}}
            >
              <Play className="w-4 h-4" />
              <span>{isRunning ? '执行中...' : '运行演示'}</span>
            </motion.button>
            
            <motion.button
              onClick={handleCopyCode}
              className="flex items-center space-x-2 px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors"
              whileHover={{ scale: 1.05 }}
              whileTap={{ scale: 0.95 }}
            >
              {copied ? <Check className="w-4 h-4" /> : <Copy className="w-4 h-4" />}
              <span>{copied ? '已复制' : '复制代码'}</span>
            </motion.button>
            
            <motion.button
              onClick={handleReset}
              className="flex items-center space-x-2 px-4 py-2 bg-gray-600 text-white rounded-lg hover:bg-gray-700 transition-colors"
              whileHover={{ scale: 1.05 }}
              whileTap={{ scale: 0.95 }}
            >
              <RotateCcw className="w-4 h-4" />
              <span>清空</span>
            </motion.button>
          </div>
        </div>
      </div>

      {/* Demo Code Display */}
      <div className="bg-white border-b border-gray-200 p-4">
        <div className="bg-gray-900 rounded-lg overflow-hidden">
          <div className="bg-gray-800 px-4 py-2 border-b border-gray-700">
            <div className="flex items-center space-x-2">
              <div className="flex space-x-1">
                <div className="w-3 h-3 bg-red-500 rounded-full"></div>
                <div className="w-3 h-3 bg-yellow-500 rounded-full"></div>
                <div className="w-3 h-3 bg-green-500 rounded-full"></div>
              </div>
              <span className="text-gray-400 text-sm font-mono">演示代码</span>
            </div>
          </div>
          <div className="p-4 max-h-40 overflow-y-auto">
            <pre className="text-green-400 font-mono text-sm whitespace-pre-wrap">
              {pattern.demoCode}
            </pre>
          </div>
        </div>
      </div>

      {/* Content */}
      <div className="flex-1 flex overflow-hidden">
        {/* Console Output */}
        <div className="flex-1 flex flex-col">
          <div className="bg-gray-900 text-green-400 p-4 border-b border-gray-700">
            <div className="flex items-center justify-between">
              <div className="flex items-center space-x-2">
                <Terminal className="w-4 h-4" />
                <span className="font-mono text-sm">控制台输出</span>
              </div>
              <div className="text-xs text-gray-500">
                {consoleMessages.length} 条消息
              </div>
            </div>
          </div>
          
          <div 
            ref={consoleRef}
            className="flex-1 bg-gray-900 p-4 overflow-y-auto scrollbar-thin"
          >
            <div className="font-mono text-sm space-y-2">
              {consoleMessages.length === 0 ? (
                <div className="text-gray-500 italic flex items-center justify-center h-32">
                  <div className="text-center">
                    <Terminal className="w-8 h-8 mx-auto mb-2 opacity-50" />
                    <div>点击"运行演示"按钮执行 {pattern.name} 代码</div>
                    <div className="text-xs mt-1">代码将在这里显示执行结果</div>
                  </div>
                </div>
              ) : (
                <AnimatePresence>
                  {consoleMessages.map((message) => (
                    <motion.div
                      key={message.id}
                      initial={{ opacity: 0, y: 10 }}
                      animate={{ opacity: 1, y: 0 }}
                      exit={{ opacity: 0, y: -10 }}
                      transition={{ duration: 0.2 }}
                      className="flex items-start space-x-3 py-1"
                    >
                      <span className="text-gray-500 text-xs mt-0.5 w-16 flex-shrink-0">
                        {message.timestamp.toLocaleTimeString()}
                      </span>
                      <div className={`flex-1 ${getMessageColor(message.type)}`}>
                        <div className="whitespace-pre-wrap break-words">
                          {message.content}
                        </div>
                      </div>
                    </motion.div>
                  ))}
                </AnimatePresence>
              )}
            </div>
          </div>
        </div>

        {/* Visualization */}
        <div className="w-96 border-l border-gray-200 bg-white">
          <div className="p-4 border-b border-gray-200">
            <button
              onClick={() => setIsVisualizationExpanded(!isVisualizationExpanded)}
              className="flex items-center space-x-2 text-gray-700 hover:text-gray-900 transition-colors w-full"
            >
              {isVisualizationExpanded ? (
                <ChevronDown className="w-4 h-4" />
              ) : (
                <ChevronRight className="w-4 h-4" />
              )}
              <Eye className="w-4 h-4" />
              <span className="font-medium">模式可视化</span>
            </button>
          </div>
          
          <AnimatePresence>
            {isVisualizationExpanded && (
              <motion.div
                initial={{ height: 0, opacity: 0 }}
                animate={{ height: 'auto', opacity: 1 }}
                exit={{ height: 0, opacity: 0 }}
                transition={{ duration: 0.3 }}
                className="overflow-hidden"
              >
                <div className="p-4">
                  <Visualization 
                    pattern={pattern} 
                    data={demoState.visualization} 
                  />
                </div>
              </motion.div>
            )}
          </AnimatePresence>
        </div>
      </div>

      {/* Status Bar */}
      <div className="bg-white border-t border-gray-200 px-4 py-2">
        <div className="flex items-center justify-between text-sm text-gray-600">
          <div className="flex items-center space-x-4">
            <span>模式: {pattern.name}</span>
            <span>难度: {pattern.difficulty}</span>
          </div>
          <div className="flex items-center space-x-2">
            {isRunning && (
              <div className="flex items-center space-x-2">
                <div className="w-2 h-2 bg-green-500 rounded-full animate-pulse"></div>
                <span>代码执行中...</span>
              </div>
            )}
          </div>
        </div>
      </div>
    </div>
  );
};

export default DemoTab;
